package com.zwkj.controller;

import cn.hutool.core.io.file.FileNameUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwkj.common.R;
import com.zwkj.design.FileSingleton;
import com.zwkj.domain.WFileT;
import com.zwkj.pojo.vo.FileParmsVo;
import com.zwkj.pojo.vo.FileVo;
import com.zwkj.pojo.vo.UserPermissionVo;
import com.zwkj.pojo.vo.WFileTVo;
import com.zwkj.service.IWFileTService;
import com.zwkj.service.IWFileVersionTService;
import com.zwkj.service.IWUserAclTService;
import com.zwkj.service.IWUserTService;
import com.zwkj.service.impl.PreviewWpsServiceImpl;
import com.zwkj.util.FileUtils;
import com.zwkj.util.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

//wps 文档预览
@RestController
@RequestMapping("/")
public class PreviewWpsController {
//    @Autowired
//    private IPreviewWpsService previewWpsService;
    @Autowired
    private PreviewWpsServiceImpl previewWpsService;
    @Autowired
    private IWUserTService userTService;
    @Autowired
    private IWFileTService wFileTService;
    @Autowired
    private IWFileVersionTService fileVersionTService;
    @Autowired
    private IWUserAclTService userAclTService;

    @Value("${wps.url}")
    private String wpsUrl;
    @Value("${wps.appid}")
    private String wpsAppId;

    @Value("${wps.host}")
    private String host;

    /**
     * 获取文件信息
     *
     * @param fileId
     * @return
     */
    @GetMapping("v3/3rd/files/{file_id}")
    private R<?> getFileById(@PathVariable("file_id") String fileId) {
        String typeStr = RequestUtils.getUserQuery(RequestUtils.getCurrentRequest(), "type");
        FileVo fileById = new FileVo();
        //预览 模拟数据
        if (typeStr == null || typeStr.equals("") || typeStr.equals("1")) {
            WFileTVo file = FileSingleton.getFile(fileId);
            fileById.setId(file.getFileId());
            fileById.setName(file.getName());
            fileById.setVersion(file.getVersion());
            fileById.setSize(Math.toIntExact(file.getSize()));
            fileById.setCreateTime(file.getCreateTimeInt());
            fileById.setModifyTime(file.getModifyTimeInt());
            fileById.setCreatorId(file.getCreatorId());
            fileById.setModifierId(file.getModifierId());
        }
        //数据编辑
        if (typeStr != null && !typeStr.equals("") && typeStr.equals("2")) {
            fileById = previewWpsService.getFileById(fileId);
        }


        return R.ok(fileById);
    }

    /**
     * 获取文件下载地址
     *
     * @param fileId
     * @return
     */
    @GetMapping("v3/3rd/files/{file_id}/download")
    private R<?> getFileDownloadUrlById(@PathVariable("file_id") String fileId) {
        String typeStr = RequestUtils.getUserQuery(RequestUtils.getCurrentRequest(), "type");
        FileVo fileById = new FileVo();
        //预览 模拟数据
        if (typeStr == null || typeStr.equals("") || typeStr.equals("1")) {
            WFileTVo file = FileSingleton.getFile(fileId);
            fileById.setId(file.getFileId());
            fileById.setName(file.getName());
            String url = host + "/console/download/" + fileId + "/" + 1 + "/" + typeStr;
            fileById.setUrl(url);
        }
        //数据编辑
        if (typeStr != null && !typeStr.equals("") && typeStr.equals("2")) {
            fileById = previewWpsService.getFileDownloadUrlById(fileId, typeStr);
        }

        return R.ok(fileById);
    }

    /**
     * 文档用户权限
     *
     * @param fileId
     * @return
     */
    @GetMapping("v3/3rd/files/{file_id}/permission")
    private R<?> getUserPermissionByFileId(@PathVariable("file_id") String fileId) {
        String typeStr = RequestUtils.getUserQuery(RequestUtils.getCurrentRequest(), "type");
        UserPermissionVo userPermissionVo = new UserPermissionVo();
        //预览 模拟数据
        if (typeStr == null || typeStr.equals("") || typeStr.equals("1")) {
            userPermissionVo.setUserRead(1);
            userPermissionVo.setUserId("1");
        }
        //数据编辑
        if (typeStr != null && !typeStr.equals("") && typeStr.equals("2")) {
            userPermissionVo = previewWpsService.getUserPermissionByFileId(fileId);
        }

        return R.ok(userPermissionVo);
    }

    /**
     * 生成编辑的url
     */
    @PostMapping("fileEdit/getPreviewEditUrl")
    public R<?> getPreviewEditUrl(@RequestBody FileParmsVo fileParmsVo) {
        String downloadUrl = fileParmsVo.getDownloadUrl();
        String officeType = FileUtils.officeType(downloadUrl);
        if (officeType == null) {
            R r = new R();
            r.setCode(500);
            r.setMessage("格式不支持");
            return r;
        }
        previewWpsService.saveNewUserAndFile(fileParmsVo);
        WFileT newFileT = wFileTService.getOne(new QueryWrapper<WFileT>().eq("table_file_id", fileParmsVo.getTableFileId()));
//        String url = wpsUrl + "/" + officeType + "/" + fileId + "?_w_appid=" + wpsAppId + "&_w_tokentype=1";
        Map<String, String> map = new HashMap<>();
        map.put("fileId", newFileT.getId().toString());
        map.put("officeType", officeType);
        return R.ok(map);

    }

    /**
     * 生成预览的url
     */
    @CrossOrigin(origins = "*")
    @GetMapping("filePreview/getPreviewUrl")
    private R<?> getPreviewUrl(@RequestParam String fileUrl) {
        String officeType = FileUtils.officeType(fileUrl);
        if (officeType == null) {
            R r = new R();
            r.setCode(500);
            r.setMessage("格式不支持");
            return r;
        }
        String fileId = FileUtils.generateId();
        String extName = FileNameUtil.extName(fileUrl);
        String mainName = FileNameUtil.mainName(fileUrl);
        LocalDateTime ctime = LocalDateTime.now();
        WFileTVo wFileTVo = new WFileTVo();
        wFileTVo.setFileId(fileId);
        wFileTVo.setDownloadUrl(fileUrl);
        wFileTVo.setVersion(1);
        wFileTVo.setName(mainName + "." + extName);
        wFileTVo.setSize(1000L);
        wFileTVo.setCreateTimeInt(Math.toIntExact(ctime.toEpochSecond(ZoneOffset.UTC)));
        wFileTVo.setModifyTimeInt(Math.toIntExact(ctime.toEpochSecond(ZoneOffset.UTC)));
        wFileTVo.setCreatorId("1");
        wFileTVo.setModifierId("1");
        FileSingleton.setFileMap(fileId, wFileTVo);

//        String url = wpsUrl + "/" + officeType + "/" + fileId + "?_w_appid=" + wpsAppId + "&_w_tokentype=1";
        Map<String, String> map = new HashMap<>();
        map.put("fileId", fileId);
        map.put("officeType", officeType);
        return R.ok(map);

    }
}
